﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.Filters;
using tcm.request;
using tcm.response;
using tcm.utils;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/phm")]
    public class PhmController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;

        public PhmController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        [HttpGet("query")]
        public DataResponse<List<PhmDetail>> query([FromQuery] PhmQueryReq req)
        {
            var dbres = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical, PharmaceuticalType, PharmaceuticalType>()
                .LeftJoin((a, b, c) => a.phm_type_id == b.id)
                .LeftJoin((a, b, c) => b.parent_id == c.id)
                .WhereIf(req.id != null, (a, b, c) => a.id == req.id)
                .WhereIf(!string.IsNullOrWhiteSpace(req.pname), (a, b, c) => a.pname.Contains(req.pname))
                .WhereIf(req.min_price != null, (a, b, c) => a.price >= req.min_price)
                .WhereIf(req.max_price != null, (a, b, c) => a.price <= req.max_price)
                .WhereIf(!string.IsNullOrEmpty(req.phm_no), (a, b, c) => a.phm_no == req.phm_no)
                .WhereIf(req.phm_type_id != null, (a, b, c) => a.phm_type_id == req.phm_type_id)
                .WhereIf(!string.IsNullOrEmpty(req.phm_address), (a, b, c) => a.phm_address == req.phm_address)
                .OrderByDescending((a, b, c) => a.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize)
                .ToList((a, b, c) => new { a, b, c});

            List<PhmDetail> list = new List<PhmDetail>();
            for (int i = 0; i < dbres.Count; i++)
            {
                PhmDetail detail = BeanUtils.copy<PhmDetail, Pharmaceutical>(dbres[i].a);
                detail.type = dbres[i].b;
                detail.bigType = dbres[i].c;
                list.Add(detail);
            }

            return HandleData(list, count);

        }

        [HttpPost("add")]
        public Result add(PharmaceuticalReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            List<Pharmaceutical> list = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical>().Where(a => a.phm_no == req.phm_no).ToList();
            if (list != null && list.Count > 0) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "药品编号重复！";
                return result;
            }

            long id = IdUtils.getId();

            Pharmaceutical pharmaceutical = BeanUtils.copy<Pharmaceutical, PharmaceuticalReq>(req);
            pharmaceutical.id = id;
            pharmaceutical.phm_type_id = (long)req.phm_type_id;
            pharmaceutical.create_date = DateTime.Now.ToLocalTime();
            pharmaceutical.update_date = DateTime.Now.ToLocalTime();

            var user = AuthManager.GetUserInfoByToken(_context, HttpContext.GetToken());
            if (user != null)
            {
                pharmaceutical.create_by = user.user_id;
                pharmaceutical.update_by = user.user_id;
            }

            int m = GCCEntrance.DBManager.GlobalDB.Insert(pharmaceutical).ExecuteAffrows();
            if (m <= 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "入库失败！";
            }
            else
            {
                result.id = id;
            }

            return result;
        }


        [HttpPut("update")]
        public Result update(PharmaceuticalReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            if (req.id == null)
            {
                result.code = 1;
                result.msg = "id为空！";
                return result;
            }

            List<Pharmaceutical> list = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical>().Where(a => a.id == req.id).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = 1;
                result.msg = "数据库中没有id:" + req.id + "的数据！";
                return result;
            }

            Pharmaceutical phm = list.First();

            BeanUtils.copy<Pharmaceutical, PharmaceuticalReq>(req, ref phm);
            phm.phm_type_id = (long)req.phm_type_id;
            phm.update_date = DateTime.Now.ToLocalTime();

            var user = AuthManager.GetUserInfoByToken(_context, HttpContext.GetToken());
            if (user != null)
            {
                phm.update_by = user.user_id;
            }


            int m = GCCEntrance.DBManager.GlobalDB.Update<Pharmaceutical>(req.id).SetSource(phm).ExecuteAffrows();

            if (m <= 0)
            {
                result.code = 1;
                result.msg = "更新失败！";
            }
            else
            {
                result.id = (long)req.id;
            }

            return result;
        }

        [HttpPost("addType")]
        public Result addPhmType(PhmTypeReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;
            long id = IdUtils.getId();
            if (req.parent_id != null && req.parent_id != 0)
            {
                // 存在父级，查询父级是否存在
                List<PharmaceuticalType> parent = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().Where(a => a.id == req.parent_id).ToList();
                if (parent == null || parent.Count == 0) 
                {
                    result.code = GlobalConstant.Failure;
                    result.msg = "父id不存在！";
                    return result;
                }

            }
            List<PharmaceuticalType> list = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().Where(a => a.type_name == req.type_name).ToList();
            if (list == null || list.Count == 0)
            {
                // 新增
                PharmaceuticalType phmTypeEntity = new PharmaceuticalType();
                phmTypeEntity.type_name = req.type_name;
                if (req.parent_id == null)
                {
                    phmTypeEntity.parent_id = 0;
                }
                else 
                {
                    phmTypeEntity.parent_id = (long)req.parent_id;
                }
               
                phmTypeEntity.id = id;

                int m = GCCEntrance.DBManager.GlobalDB.Insert(phmTypeEntity).ExecuteAffrows();
                if (m <= 0)
                {
                    result.code = 1;
                    result.msg = "入库失败！";
                }
                else
                {
                    result.id = id;
                }

            }
            else 
            {
                result.msg = "药品类型：" + req.type_name + "已存在！";
                result.code = GlobalConstant.Failure;
            }
            return result;
        }


        [HttpDelete("delType/{id}")]
        public Result delType([FromRoute] long id)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            if (id == null || id == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "id不能为空！";
                return result;
            }

            // 存在父级，查询父级是否存在
            List<PharmaceuticalType> list = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType, Pharmaceutical>()
                .InnerJoin((a, b) => a.id == b.phm_type_id).Where((a, b) => a.id == id).ToList();
            if (list == null || list.Count == 0)
            {
                _=GCCEntrance.DBManager.GlobalDB.Delete<PharmaceuticalType>().Where(a => a.id == id).ExecuteAffrows();
                result.msg = "删除成功！";
            }
            else 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "药品类型下存在药品，无法删除！";
                return result;
            }

            return result;
        }

        [HttpGet("queryType")]
        public DataResponse<List<PharmaceuticalType>> queryType(long? parent_id)
        {
            List<PharmaceuticalType> dbres = new List<PharmaceuticalType>();
            if (parent_id == null)
            {
                // 查询所有
                dbres = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().ToList();
            }
            else
            {
                dbres = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().Where(a => a.parent_id == parent_id).ToList();
            }
            return HandleData(dbres);
        }

        [HttpGet("queryAllType")]
        public List<PhmType> queryAllType()
        {
            List<PhmType> list = new List<PhmType>();
            List<PharmaceuticalType> dbres = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().Where(a => a.parent_id == null || a.parent_id == 0).ToList();
            for (int i =0; i < dbres.Count; i++) 
            {
                long id = dbres[i].id;
                List<PharmaceuticalType> types = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>().Where(a => a.parent_id == id).ToList();

                PhmType type = new PhmType();
                type.parent_id = dbres[i].parent_id;
                type.id = dbres[i].id;
                type.type_name = dbres[i].type_name;
                type.childern = types;
                list.Add(type);
            }
            
            return list;
        }

        //[HttpGet("queryTypeByPage")]
        //public DataResponse<List<PharmaceuticalType>> queryTypeByPage([FromQuery] PageRequestBase req)
        //{
        //    var dbres = GCCEntrance.DBManager.GlobalDB.Select<PharmaceuticalType>()
        //        .Count(out var count)
        //        .Page(req.PageIndex ?? 1, req.PageSize)
        //        .ToList();
        //    return HandleData(dbres, count);
        //}

    }
}
